package ten;

public class LockTest {

    Lock lock = new Lock();

    public void a() throws InterruptedException {
        lock.lock();
        doSomething();
        lock.unlock();
    }

    private void doSomething() throws InterruptedException {
        lock.lock();
        System.out.println("doSomething");
        lock.unlock();
    }

    public void test(){
        synchronized (this){
            while (true){
                synchronized (this){
                    System.out.println("ReentrantLock!");
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
//        new LockTest().test();
        new LockTest().a();
    }
}

class Lock{
    //是否占用
    private boolean isLocked = false;
    //使用锁
    public synchronized void lock() throws InterruptedException {
        while (isLocked){
            wait();
        }
        isLocked = true;
    }
    public synchronized void unlock(){
        isLocked = false;
        notify();
    }
}